using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using WPF_MVVM_Test.MVVM_Model.Bom;
using WPF_MVVM_Test.MVVM_Model.Material;
using WPF_MVVM_Test.Services.Material;

namespace WPF_MVVM_Test.MVVM_View.Bom
{
    /// <summary>
    /// MaterialSelectionDialog.xaml 的交互逻辑
    /// </summary>
    public partial class MaterialSelectionDialog : Window
    {
        private MaterialSelectionViewModel _viewModel;

        public MaterialSelectionDialog()
        {
            InitializeComponent();
            _viewModel = new MaterialSelectionViewModel();
            DataContext = _viewModel;
        }

        /// <summary>
        /// 获取选中的物料项
        /// </summary>
        public List<BomItemModel> SelectedBomItems => _viewModel.GetSelectedBomItems();

        private void ConfirmButton_Click(object sender, RoutedEventArgs e)
        {
            var selectedItems = _viewModel.GetSelectedBomItems();
            if (selectedItems.Count == 0)
            {
                MessageBox.Show("请至少选择一个物料！", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            DialogResult = true;
            Close();
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
            Close();
        }
    }

    /// <summary>
    /// 物料选择ViewModel
    /// </summary>
    public class MaterialSelectionViewModel : INotifyPropertyChanged
    {
        private readonly MaterialService _materialService;
        private ObservableCollection<MaterialSelectionItem> _materialItems;
        private string _searchKeyword = string.Empty;
        private string _selectedUnit = string.Empty;
        private string _selectedType = string.Empty;
        private string _selectedProperty = string.Empty;
        private bool _isAllSelected;
        private int _currentPage = 1;
        private int _totalPages = 1;
        private int _pageSize = 10;
        private int _totalItems = 0;

        public MaterialSelectionViewModel()
        {
            _materialService = new MaterialService();
            _materialItems = new ObservableCollection<MaterialSelectionItem>();

            // 初始化筛选选项
            UnitOptions = new ObservableCollection<string> { "全部", "个", "米", "千克", "升", "平方米" };
            TypeOptions = new ObservableCollection<string> { "全部", "原材料", "半成品", "成品" };
            PropertyOptions = new ObservableCollection<string> { "全部", "外购", "自制", "委外" };

            // 初始化命令
            SearchCommand = new RelayCommand(ExecuteSearch);
            ResetCommand = new RelayCommand(ExecuteReset);
            SelectAllCommand = new RelayCommand(ExecuteSelectAll);
            FirstPageCommand = new RelayCommand(ExecuteFirstPage, CanExecuteFirstPage);
            PreviousPageCommand = new RelayCommand(ExecutePreviousPage, CanExecutePreviousPage);
            NextPageCommand = new RelayCommand(ExecuteNextPage, CanExecuteNextPage);
            LastPageCommand = new RelayCommand(ExecuteLastPage, CanExecuteLastPage);

            // 加载数据
            LoadMaterialsAsync();
        }

        #region 属性

        public ObservableCollection<MaterialSelectionItem> MaterialItems
        {
            get => _materialItems;
            set
            {
                _materialItems = value;
                OnPropertyChanged(nameof(MaterialItems));
                UpdateSelectedCount();
            }
        }

        public string SearchKeyword
        {
            get => _searchKeyword;
            set
            {
                _searchKeyword = value;
                OnPropertyChanged(nameof(SearchKeyword));
            }
        }

        public string SelectedUnit
        {
            get => _selectedUnit;
            set
            {
                _selectedUnit = value;
                OnPropertyChanged(nameof(SelectedUnit));
            }
        }

        public string SelectedType
        {
            get => _selectedType;
            set
            {
                _selectedType = value;
                OnPropertyChanged(nameof(SelectedType));
            }
        }

        public string SelectedProperty
        {
            get => _selectedProperty;
            set
            {
                _selectedProperty = value;
                OnPropertyChanged(nameof(SelectedProperty));
            }
        }

        public bool IsAllSelected
        {
            get => _isAllSelected;
            set
            {
                _isAllSelected = value;
                OnPropertyChanged(nameof(IsAllSelected));
            }
        }

        public int CurrentPage
        {
            get => _currentPage;
            set
            {
                _currentPage = value;
                OnPropertyChanged(nameof(CurrentPage));
                OnPropertyChanged(nameof(PageInfo));
                UpdatePageCommands();
            }
        }

        public int TotalPages
        {
            get => _totalPages;
            set
            {
                _totalPages = value;
                OnPropertyChanged(nameof(TotalPages));
                OnPropertyChanged(nameof(PageInfo));
                UpdatePageCommands();
            }
        }

        public int TotalItems
        {
            get => _totalItems;
            set
            {
                _totalItems = value;
                OnPropertyChanged(nameof(TotalItems));
                OnPropertyChanged(nameof(PageInfo));
            }
        }

        public string PageInfo => $"共 {TotalItems} 条";

        public string SelectedCountText => $"已选择 {MaterialItems?.Count(x => x.IsSelected) ?? 0} 项";

        public ObservableCollection<string> UnitOptions { get; }
        public ObservableCollection<string> TypeOptions { get; }
        public ObservableCollection<string> PropertyOptions { get; }

        #endregion

        #region 命令

        public ICommand SearchCommand { get; }
        public ICommand ResetCommand { get; }
        public ICommand SelectAllCommand { get; }
        public ICommand FirstPageCommand { get; }
        public ICommand PreviousPageCommand { get; }
        public ICommand NextPageCommand { get; }
        public ICommand LastPageCommand { get; }

        #endregion

        #region 命令执行方法

        private async void ExecuteSearch()
        {
            CurrentPage = 1;
            await LoadMaterialsAsync();
        }

        private async void ExecuteReset()
        {
            SearchKeyword = string.Empty;
            SelectedUnit = string.Empty;
            SelectedType = string.Empty;
            SelectedProperty = string.Empty;
            CurrentPage = 1;
            await LoadMaterialsAsync();
        }

        private void ExecuteSelectAll()
        {
            foreach (var item in MaterialItems)
            {
                item.IsSelected = IsAllSelected;
            }
            UpdateSelectedCount();
        }

        private async void ExecuteFirstPage()
        {
            CurrentPage = 1;
            await LoadMaterialsAsync();
        }

        private async void ExecutePreviousPage()
        {
            if (CurrentPage > 1)
            {
                CurrentPage--;
                await LoadMaterialsAsync();
            }
        }

        private async void ExecuteNextPage()
        {
            if (CurrentPage < TotalPages)
            {
                CurrentPage++;
                await LoadMaterialsAsync();
            }
        }

        private async void ExecuteLastPage()
        {
            CurrentPage = TotalPages;
            await LoadMaterialsAsync();
        }

        private bool CanExecuteFirstPage() => CurrentPage > 1;
        private bool CanExecutePreviousPage() => CurrentPage > 1;
        private bool CanExecuteNextPage() => CurrentPage < TotalPages;
        private bool CanExecuteLastPage() => CurrentPage < TotalPages;

        private void UpdatePageCommands()
        {
            (FirstPageCommand as RelayCommand)?.RaiseCanExecuteChanged();
            (PreviousPageCommand as RelayCommand)?.RaiseCanExecuteChanged();
            (NextPageCommand as RelayCommand)?.RaiseCanExecuteChanged();
            (LastPageCommand as RelayCommand)?.RaiseCanExecuteChanged();
        }

        #endregion

        #region 数据加载

        private async System.Threading.Tasks.Task LoadMaterialsAsync()
        {
            try
            {
                var response = await _materialService.GetMaterialsByCategoryAsync(
                    categoryId: "",
                    pageIndex: CurrentPage,
                    pageSize: _pageSize
                );

                if (response.IsSuc)
                {
                    MaterialItems.Clear();

                    // 根据搜索条件过滤数据
                    var filteredData = response.Data.Data.AsEnumerable();

                    if (!string.IsNullOrEmpty(SearchKeyword))
                    {
                        filteredData = filteredData.Where(m => 
                            m.MaterialName.Contains(SearchKeyword, StringComparison.OrdinalIgnoreCase) ||
                            m.MaterialNumber.Contains(SearchKeyword, StringComparison.OrdinalIgnoreCase));
                    }

                    if (!string.IsNullOrEmpty(SelectedUnit) && SelectedUnit != "全部")
                    {
                        filteredData = filteredData.Where(m => m.Unit == SelectedUnit);
                    }

                    if (!string.IsNullOrEmpty(SelectedType) && SelectedType != "全部")
                    {
                        filteredData = filteredData.Where(m => GetMaterialTypeText(m.MaterialType) == SelectedType);
                    }

                    if (!string.IsNullOrEmpty(SelectedProperty) && SelectedProperty != "全部")
                    {
                        filteredData = filteredData.Where(m => m.MaterialProperty == SelectedProperty);
                    }

                    foreach (var item in filteredData)
                    {
                        var selectionItem = new MaterialSelectionItem
                        {
                            Id = item.Id,
                            MaterialNumber = item.MaterialNumber,
                            MaterialName = item.MaterialName,
                            SpecificationModel = item.SpecificationModel,
                            Unit = item.Unit,
                            MaterialType = GetMaterialTypeText(item.MaterialType),
                            MaterialProperty = item.MaterialProperty,
                            Quantity = 1,
                            LossRate = 0
                        };

                        // 订阅选择状态变化事件
                        selectionItem.PropertyChanged += (s, e) =>
                        {
                            if (e.PropertyName == nameof(MaterialSelectionItem.IsSelected))
                            {
                                UpdateSelectedCount();
                            }
                        };

                        MaterialItems.Add(selectionItem);
                    }

                    TotalItems = response.Data.TotalCount;
                    TotalPages = response.Data.TotalPage;
                }
                else
                {
                    // 如果API失败，加载测试数据
                    LoadTestData();
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"加载物料数据异常: {ex.Message}");
                // 异常时加载测试数据
                LoadTestData();
            }
        }

        private void LoadTestData()
        {
            MaterialItems.Clear();

            var testData = new[]
            {
                new MaterialSelectionItem
                {
                    Id = Guid.NewGuid().ToString(),
                    MaterialNumber = "WL025",
                    MaterialName = "物料一",
                    SpecificationModel = "蓝色",
                    Unit = "个",
                    MaterialType = "生产物料",
                    MaterialProperty = "采购",
                    Quantity = 1,
                    LossRate = 0
                },
                new MaterialSelectionItem
                {
                    Id = Guid.NewGuid().ToString(),
                    MaterialNumber = "WL025",
                    MaterialName = "物料二",
                    SpecificationModel = "蓝色",
                    Unit = "个",
                    MaterialType = "生产物料",
                    MaterialProperty = "采购",
                    Quantity = 1,
                    LossRate = 0
                },
                new MaterialSelectionItem
                {
                    Id = Guid.NewGuid().ToString(),
                    MaterialNumber = "WL025",
                    MaterialName = "物料三",
                    SpecificationModel = "蓝色",
                    Unit = "个",
                    MaterialType = "生产物料",
                    MaterialProperty = "采购",
                    Quantity = 1,
                    LossRate = 0
                },
                new MaterialSelectionItem
                {
                    Id = Guid.NewGuid().ToString(),
                    MaterialNumber = "WL025",
                    MaterialName = "物料四",
                    SpecificationModel = "蓝色",
                    Unit = "个",
                    MaterialType = "生产物料",
                    MaterialProperty = "采购",
                    Quantity = 1,
                    LossRate = 0
                },
                new MaterialSelectionItem
                {
                    Id = Guid.NewGuid().ToString(),
                    MaterialNumber = "WL025",
                    MaterialName = "物料五",
                    SpecificationModel = "蓝色",
                    Unit = "个",
                    MaterialType = "生产物料",
                    MaterialProperty = "采购",
                    Quantity = 1,
                    LossRate = 0
                }
            };

            foreach (var item in testData)
            {
                // 订阅选择状态变化事件
                item.PropertyChanged += (s, e) =>
                {
                    if (e.PropertyName == nameof(MaterialSelectionItem.IsSelected))
                    {
                        UpdateSelectedCount();
                    }
                };

                MaterialItems.Add(item);
            }

            TotalItems = MaterialItems.Count;
            TotalPages = 1;
        }

        #endregion

        #region 辅助方法

        private string GetMaterialTypeText(int materialType)
        {
            return materialType switch
            {
                1 => "原材料",
                2 => "半成品",
                3 => "成品",
                _ => "未知"
            };
        }

        private void UpdateSelectedCount()
        {
            OnPropertyChanged(nameof(SelectedCountText));
            
            // 更新全选状态
            var selectedCount = MaterialItems?.Count(x => x.IsSelected) ?? 0;
            var totalCount = MaterialItems?.Count ?? 0;
            
            if (totalCount == 0)
            {
                IsAllSelected = false;
            }
            else if (selectedCount == totalCount)
            {
                IsAllSelected = true;
            }
            else
            {
                IsAllSelected = false;
            }
        }

        /// <summary>
        /// 获取选中的BOM项
        /// </summary>
        public List<BomItemModel> GetSelectedBomItems()
        {
            var selectedItems = MaterialItems.Where(x => x.IsSelected).ToList();
            var bomItems = new List<BomItemModel>();

            foreach (var item in selectedItems)
            {
                bomItems.Add(new BomItemModel
                {
                    MaterialId = item.Id,
                    ParentItemId = Guid.Empty.ToString(), // 根据需要设置
                    Quantity = item.Quantity,
                    LossRate = item.LossRate,
                    InOutType = 1,
                    Unit = item.Unit,
                    Remark = item.Remark
                });
            }

            return bomItems;
        }

        #endregion

        public event PropertyChangedEventHandler? PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    /// <summary>
    /// 行索引转换器
    /// </summary>
    public class RowIndexConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is MaterialSelectionItem item)
            {
                var dataGrid = parameter as System.Windows.Controls.DataGrid;
                if (dataGrid != null)
                {
                    var index = dataGrid.Items.IndexOf(item);
                    return (index + 1).ToString();
                }
            }
            return "1";
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

    /// <summary>
    /// 简单的RelayCommand实现
    /// </summary>
    public class RelayCommand : ICommand
    {
        private readonly Action _execute;
        private readonly Func<bool>? _canExecute;

        public RelayCommand(Action execute, Func<bool>? canExecute = null)
        {
            _execute = execute ?? throw new ArgumentNullException(nameof(execute));
            _canExecute = canExecute;
        }

        public event EventHandler? CanExecuteChanged;

        public bool CanExecute(object? parameter)
        {
            return _canExecute?.Invoke() ?? true;
        }

        public void Execute(object? parameter)
        {
            _execute();
        }

        public void RaiseCanExecuteChanged()
        {
            CanExecuteChanged?.Invoke(this, EventArgs.Empty);
        }
    }
}